<?php

class Front_AuthController extends Zend_Controller_Action
{

    public function init()
    {
        $this->view->baseUrl = $this->_request->getBaseUrl();

    }

    public function indexAction()
    {
    	$storage = new Zend_Auth_Storage_Session();
    	$data = $storage->read();
    	
    	if(!$data){
    		$this->_redirect('front/auth/login');
    	}else if(!$formData->isAdmin){
	    	$this->view->username = $data->username;
	    	$this->_redirect('front/boutique/index');
    	}else{
    		$this->_redirect('front/auth/login');
    	}
    }

    public function loginAction()
    {
    	$users = new Front_Model_DbTable_User();
    	$form = new Front_Form_Auth_Login();
    	$this->view->form = $form;
    	if($this->getRequest()->isPost()){
    		if($form->isValid($_POST)){
    			$data = $form->getValues();
    			
    			$auth = Zend_Auth::getInstance();
    			$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'user');
    			
    			$authAdapter->setIdentityColumn('username')
    						->setCredentialColumn('password');
    			$authAdapter->setIdentity($data['username'])
    						->setCredential($data['password']);
    			
    			$result = $auth->authenticate($authAdapter);
    			if($result->isValid()){
    				
    				$storage = new Zend_Auth_Storage_Session();
    				$storage->write($authAdapter->getResultRowObject());
    				$this->_redirect('front/auth/index');
    			} else {
    				$this->view->errorMessage = "Username ou password invalid Veuillez réessayer encore.";
    			}
    		}
    	}
        
    }

    public function logoutAction()
    {
    	$storage = new Zend_Auth_Storage_Session();
    	$storage->clear();
    	$this->_redirect('front');
    }

    public function signupAction()
    {
    	$users = new Front_Model_DbTable_User();
    	$form = new Front_Form_Auth_Registration();
    	$this->view->form=$form;
    	
    	if($this->getRequest()->isPost()){
    		if($form->isValid($_POST)){
    			$data = $form->getValues();
    			if($data['password'] != $data['confirmPassword']){
    				$this->view->errorMessage = "Le mot de passe et le mot de passe de confirmation ne correspondent pas.";
    				return;
    			}
    			if($users->checkUnique($data['username'])){
    				$this->view->errorMessage = "Nom déjà prit. Veuillez choisir un autre.";
    				return;
    			}
    			unset($data['confirmPassword']);
    			$users->insert($data);
    			$this->_redirect('front/auth/login');
    		}
    	}
    }


}



